<template>
	<u-index-list :index-list="indexList">
		<view class="p-20">
			<u-search placeholder="请输入搜索内容" v-model="keyword" bgColor="#fff" borderColor="#CDCDCD" searchIconSize="29"
				searchIconColor="#999999" placeholderColor="#999999" @custom="searchTap" @clear="searchTap" >
			</u-search>
		</view>
		<template v-for="(item, index) in indexList" :key="index">
			<u-index-item>
				<u-index-anchor :text="indexList[index]" />
				<view class="list-cell" v-for="(cell,i) in list[item]" @click="confirm(cell)">
					{{cell.name}}
				</view>
			</u-index-item>
		</template>
	</u-index-list>
</template>

<script setup lang="ts">

	import { ref } from "vue";
	import pinyin from "js-pinyin"
	import { onLoad } from '@dcloudio/uni-app';
	import { isNullorEmpty } from '@/utils/global'
	import { categorySimpleQuery } from '@/services/api/pet';
	const indexList = ref([])
	const keyword = ref<string>('')
	const ids = ref()
	const list = ref([])
	onLoad((options : any) => {
		ids.value = options.id
		getBreed()
	});
	//获取品种
	async function getBreed() {
		const { data } = await categorySimpleQuery(
			{ parentId: ids.value, name: keyword.value }
		);
		getListByPinyinFirstLetter(data)
	}

	function getListByPinyinFirstLetter(data) {
		const newList = {};
		for (const item of data) {
			let firstLetter;
			if (/[a-zA-Z]/.test(item.name.charAt(0))) {
				firstLetter = item.name.charAt(0).toUpperCase();
			} else {
				// const pinyinArray = pinyin(item.name, {
				// 	style: pinyin.STYLE_FIRST_LETTER,
				// });
				const pinyinArray = pinyin.getFullChars(item.name).charAt(0)
				if (pinyinArray.length > 0) {
					firstLetter = /[a-zA-Z]/.test(pinyinArray[0][0].toUpperCase()) ? pinyinArray[0][0].toUpperCase() :
						"#";
				} else {

					firstLetter = "#";
				}
			}

			if (!newList[firstLetter]) {
				newList[firstLetter] = [];
			}
			newList[firstLetter].push(item);
		}
		const sortedKeys = Object.keys(newList).sort((a, b) => {
			if (a === '#') return 1;
			if (b === '#') return -1;
			return a.localeCompare(b);
		});
		const sortedNewList = {};
		for (const key of sortedKeys) {
			sortedNewList[key] = newList[key];
		}
		indexList.value = sortedKeys
		list.value = sortedNewList;
	}
	const searchTap = (e) => {
		if (!isNullorEmpty(keyword.value)) {
			keyword.value = e
			getBreed()
		} else {
			uni.showToast({
				title: "请输入搜索内容",
				icon: "none"
			})
		}

	}
	const confirm = (e) => {
		uni.$emit('updateNote', e);
		uni.navigateBack({
			delta: 1
		})
	}
</script>

<style lang="scss" scoped>
	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;
	}
</style>